package com.coze.lg.cozeagent.controller.oldtest;

import com.coze.lg.cozeagent.controller.AipSpeech;
import com.coze.openapi.client.audio.speech.CreateSpeechReq;
import com.coze.openapi.client.audio.speech.CreateSpeechResp;
import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.service.CozeAPI;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;

public class SessionSocket {
    private final Socket clientSocket;
    private final AipSpeech aipSpeech;
    private final CozeAPI cozeAPI;
    private boolean isOpenSpeak = false;

    // 用于标记是否有活跃对话
    private final AtomicBoolean hasActiveChat = new AtomicBoolean(false);
    // 用于存储当前对话线程
    private volatile Thread currentChatThread = null;

    public SessionSocket(Socket clientSocket, AipSpeech aipSpeech, CozeAPI cozeAPI) {
        this.clientSocket = clientSocket;
        this.aipSpeech = aipSpeech;
        this.cozeAPI = cozeAPI;
    }

    public void do_start() {
        try {
            do_read_pcm();
        } catch (IOException e) {
            System.out.println("有连接丢失");
        }
    }

    public void do_read_pcm() throws IOException {
        System.out.println("启动读取");
        InputStream inn = clientSocket.getInputStream();
        byte[] message = inn.readAllBytes();    // 阻塞的
        System.out.println("读取完毕");
        JSONObject res = aipSpeech.asr(message, "pcm", 16000, null);
        String result = res.toString(2);
        System.out.println(result);
        do_coze_speech(result);
    }
    public void do_coze_speech(String result) throws IOException {
        // 棫查是否是唤醒词或已经在对话中
        if (result.contains("小光") || isOpenSpeak) {
            isOpenSpeak = true;
            System.out.println("钉子");

            // 如果有正在进行的对话，先中断它
            if (hasActiveChat.get()) {
                System.out.println("中断当前对话，处理新消息");
                try {
                    // 如果有对话线程，中断它
                    if (currentChatThread != null && currentChatThread.isAlive()) {
                        currentChatThread.interrupt();
                    }
                } catch (Exception e) {
                    System.err.println("中断对话时出错: " + e.getMessage());
                }
            }
            // 在新线程中处理聊天请求
            Thread chatThread = new Thread(() -> {
                try {
                    hasActiveChat.set(true);
                    currentChatThread = Thread.currentThread();
                    // 使用原始的客户端socket处理聊天和语音回复
                    handleChatWithSpeech(result, "7537946388177403947", clientSocket);
                } catch (Exception e) {
                    if (e instanceof InterruptedException ||
                            e.getCause() instanceof InterruptedException ||
                            e instanceof java.io.InterruptedIOException) {
                        System.out.println("对话被中断");
                    } else {
                        System.err.println("聊天过程中出错: " + e.getMessage());
                        e.printStackTrace();
                    }
                } finally {
                    hasActiveChat.set(false);
                    currentChatThread = null;
                }
            });

            chatThread.start();

            // 处理再见命令
            if (result.contains("再见")) {
                isOpenSpeak = false;
                System.out.println("结束对话模式");
            }
        }
    }
    /**
     * 处理聊天并生成语音回复
     * @param userMessage 用户消息
     * @param botId 机器人ID
     * @param clientSocket 客户端Socket
     */
    private void handleChatWithSpeech(String userMessage, String botId, Socket clientSocket) {
        OutputStream out = null;
        try {
            out = clientSocket.getOutputStream();

            CreateChatReq req = CreateChatReq.builder()
                    .botID(botId)
                    .userID("123") // 使用固定用户ID
                    .messages(Collections.singletonList(Message.buildUserQuestionText(userMessage)))
                    .build();

            StringBuilder fullResponse = new StringBuilder();

            // 流式接收聊天回复
            OutputStream finalOut = out;
            cozeAPI.chat().stream(req).subscribe(
                    event -> {
                        try {
                            if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                                String content = event.getMessage().getContent();
                                fullResponse.append(content);
                                System.out.print(content);

                                // 实时将文本转为语音并发送给客户端
                                byte[] speechData = textToSpeech(content);
                                if (speechData != null && speechData.length > 0) {
                                    // 先发送数据长度
                                    finalOut.write(intToByteArray(speechData.length));
                                    // 再发送实际语音数据
                                    finalOut.write(speechData);
                                    finalOut.flush();
                                    System.out.println("发送语音数据，长度: " + speechData.length);
                                    String s = new String(speechData);
                                    System.out.println(s);
                                }
                            }

                            if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
                                System.out.println("\n对话完成，总Token数: " + event.getChat().getUsage().getTokenCount());
                                // 发送结束标记
                                finalOut.write(intToByteArray(0)); // 0表示结束
                                finalOut.flush();
                            }
                        } catch (Exception e) {
                            System.err.println("处理聊天事件时出错: " + e.getMessage());
                            // 不要抛出异常，继续处理其他事件
                        }
                    },
                    error -> {
                        System.err.println("聊天流错误: " + error.getMessage());
                        error.printStackTrace();
                    },
                    () -> {
                        System.out.println("聊天流完成");
                    }
            );

            // 等待一段时间确保对话完成
            Thread.sleep(3000);

        } catch (Exception e) {
            System.err.println("处理聊天和语音时出错: " + e.getMessage());
            e.printStackTrace();
        }
        // 注意：不要在这里关闭out流，因为clientSocket还在主循环中使用
    }
//    public void do_write_pcm(String content) throws IOException {
//        OutputStream finalOut = clientSocket.getOutputStream();
//        // 实时将文本转为语音并发送给客户端
//        byte[] speechData = textToSpeech(content);
//        if (speechData.length > 0) {
//            // 先发送数据长度
//            finalOut.write(intToByteArray(speechData.length));
//            // 再发送实际语音数据
//            finalOut.write(speechData);
//            finalOut.flush();
//            System.out.println("发送语音数据，长度: " + speechData.length);
//            String s = new String(speechData);
//            System.out.println(s);
//        }
//    }
    private byte[] textToSpeech(String text) {
        try {
            // 过滤掉空内容或特殊字符
            if (text == null || text.trim().isEmpty() ||
                    text.trim().equals("\n") || text.trim().equals("\r\n")) {
                return new byte[0];
            }

            CreateSpeechReq req = CreateSpeechReq.builder()
                    .input(text.trim())
                    .voiceID("7426720361733013513")
                    .sampleRate(16000)
                    .build();

            // 调用Coze文字转语音API
            CreateSpeechResp response = cozeAPI.audio().speech().create(req);
            if (response != null && response.getResponse() != null) {
                byte[] data = response.getResponse().bytes();
                System.out.println("语音数据生成成功，长度: " + data.length);
                return data;
            }

        } catch (Exception e) {
            System.err.println("文字转语音失败: " + e.getMessage());
            e.printStackTrace();
        }
        return new byte[0];
    }
    /**
     * 将整数转换为字节数组（大端序）
     */
    private byte[] intToByteArray(int value) {
        return new byte[] {
                (byte)(value >> 24),
                (byte)(value >> 16),
                (byte)(value >> 8),
                (byte)value
        };
    }
}
